package org.noote.libs.computervision.detection.movement;

import org.noote.libs.computervision.buffer.Buffer8888XRGB;

public class MovementDetection_Grid extends MovementDetection_Map {
	
	int _iGridX=0, _iGridY=0;
	
	float [] _gridActivity = null;
	
	public MovementDetection_Grid()
	{
		super();
	}
	
	public MovementDetection_Grid(int iGridX, int iGridY)
	{
		super();
		createGrid(iGridX, iGridY);
	}

	public boolean createGrid(int iGridX, int iGridY)
	{
		if(iGridX < 1 || iGridY < 1)
			return false;

		if(iGridX != _iGridX || iGridY != _iGridY)
		{
			_gridActivity = new float[iGridX*iGridY];
			if(_gridActivity == null)
				return false;
			
			for(int c=0; c<_gridActivity.length; c++)
			{
				_gridActivity[c] = 0;
			}

			_iGridX = iGridX;
			_iGridY = iGridY;
		}
		
		return true;
	}
	
	public int getColumnCount()
	{
		return _iGridX;
	}

	public int getRowCount()
	{
		return _iGridY;
	}

	public float getActivity(int iX, int iY)
	{
		if(_gridActivity != null
				&& iX>=0 && iX<_iGridX
				&& iY>=0 && iY<_iGridY)
		{
			return _gridActivity[iY*_iGridX + iX];
		}
		
		return -1.0f;
	}
	
    @Override
	public boolean push(Buffer8888XRGB xrgb, float fTimeSlice)
	{
		if(_gridActivity == null) return false;
		
		if(!super.push(xrgb, fTimeSlice)) return false;
		
		int iGridPixelX = _width/_iGridX;
		int iGridPixelY = _height/_iGridY;

		// calcul cell activity
		for(int gy=0; gy<_iGridY;  gy++)
		{
			for(int gx=0; gx<_iGridX;  gx++)
			{
				int idx = _iGridX*gy + gx;
				
				_gridActivity[idx] = 0.0f;

				int idxBase = (gy*_iGridY)*_width+gx*_iGridX;
				
				float fA = 0;
				for(int py=0; py<iGridPixelY; py++)
				{
					int idxData = idxBase + py*_width;
					
					for(int px=0; px<iGridPixelX; px++)
					{
						fA += _i8I[idxData+px]; // cumul
					}
				}
				fA /= 255.0f; // normalize

				_gridActivity[idx] = fA/(float)(iGridPixelX*iGridPixelY);
			}
		}

		return true;
	}
}
